{
  "nbformat": 4,
  "nbformat_minor": 0,
  "metadata": {
    "colab": {
      "name": "first-tflite.ipynb",
      "provenance": [],
      "include_colab_link": true
    },
    "kernelspec": {
      "name": "python3",
      "display_name": "Python 3"
    },
    "accelerator": "GPU"
  },
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "view-in-github",
        "colab_type": "text"
      },
      "source": [
        "<a href=\"https://colab.research.google.com/github/lmoroney/tfbook/blob/master/chapter12/first-tflite.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "zX4Kg8DUTKWO",
        "colab_type": "code",
        "colab": {}
      },
      "source": [
        "#@title Licensed under the Apache License, Version 2.0 (the \"License\");\n",
        "# you may not use this file except in compliance with the License.\n",
        "# You may obtain a copy of the License at\n",
        "#\n",
        "# https://www.apache.org/licenses/LICENSE-2.0\n",
        "#\n",
        "# Unless required by applicable law or agreed to in writing, software\n",
        "# distributed under the License is distributed on an \"AS IS\" BASIS,\n",
        "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
        "# See the License for the specific language governing permissions and\n",
        "# limitations under the License."
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "D1J15Vh_1Jih",
        "colab_type": "code",
        "cellView": "both",
        "colab": {}
      },
      "source": [
        "try:\n",
        "  # %tensorflow_version only exists in Colab.\n",
        "  %tensorflow_version 2.x\n",
        "except Exception:\n",
        "  pass\n"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "O6k2Pg0gTYB8",
        "colab_type": "code",
        "colab": {}
      },
      "source": [
        "import tensorflow as tf\n",
        "import numpy as np\n",
        "from tensorflow.keras import Sequential\n",
        "from tensorflow.keras.layers import Dense"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "YAwdHf6ySQGt",
        "colab_type": "code",
        "colab": {}
      },
      "source": [
        "l0 = Dense(units=1, input_shape=[1])\n",
        "model = Sequential([l0])\n",
        "model.compile(optimizer='sgd', loss='mean_squared_error')\n",
        "\n",
        "xs = np.array([-1.0, 0.0, 1.0, 2.0, 3.0, 4.0], dtype=float)\n",
        "ys = np.array([-3.0, -1.0, 1.0, 3.0, 5.0, 7.0], dtype=float)\n",
        "\n",
        "model.fit(xs, ys, epochs=500)\n",
        "\n",
        "print(model.predict([10.0]))\n",
        "print(\"Here is what I learned: {}\".format(l0.get_weights()))"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "SOs_IDM6ToaM",
        "colab_type": "code",
        "colab": {}
      },
      "source": [
        "export_dir = 'saved_model/1'\n",
        "tf.saved_model.save(model, export_dir)"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "lWSlkprhTsWE",
        "colab_type": "code",
        "colab": {}
      },
      "source": [
        "\n",
        "# Convert the model.\n",
        "converter = tf.lite.TFLiteConverter.from_saved_model(export_dir)\n",
        "tflite_model = converter.convert()"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "lsaEjJfrTujk",
        "colab_type": "code",
        "colab": {}
      },
      "source": [
        "import pathlib\n",
        "tflite_model_file = pathlib.Path('model.tflite')\n",
        "tflite_model_file.write_bytes(tflite_model)"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "fseX4pkhTzS0",
        "colab_type": "code",
        "colab": {}
      },
      "source": [
        "# Load TFLite model and allocate tensors.\n",
        "interpreter = tf.lite.Interpreter(model_content=tflite_model)\n",
        "interpreter.allocate_tensors()\n",
        "\n",
        "# Get input and output tensors.\n",
        "input_details = interpreter.get_input_details()\n",
        "output_details = interpreter.get_output_details()\n",
        "print(input_details)\n",
        "print(output_details)"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "k_Ij8_BvU0KV",
        "colab_type": "code",
        "colab": {}
      },
      "source": [
        "to_predict = np.array([[10.0]], dtype=np.float32)\n",
        "print(to_predict)\n",
        "interpreter.set_tensor(input_details[0]['index'], to_predict)\n",
        "interpreter.invoke()\n",
        "tflite_results = interpreter.get_tensor(output_details[0]['index'])\n",
        "print(tflite_results)"
      ],
      "execution_count": 0,
      "outputs": []
    }
  ]
}
